#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File: api_core.py
# Date: 2025/4/17
# Author: zhang shuirong
import json
import os
import sys

from fastapi import FastAPI, Security
from pydantic import BaseModel
from fastapi.security import APIKeyHeader
from log_config import get_logger
from miniqmt_core import qmt_core
import requests

# 获取日志记录器
logger = get_logger()

app = FastAPI()
api_key_header = APIKeyHeader(name="X-API-Key")

# 硬编码密钥 🔑
VALID_API_KEY = "zsr_trading_2025"


class Position(BaseModel):
    stock_info: dict
    trade_time: str
    operation: str


def validate_api_key(input_key: str):
    return input_key == VALID_API_KEY


@app.post("/adjust_position")
async def adjust_position(positions: Position, api_key: str = Security(api_key_header)):
    logger.info(f"接收到请求，API Key: {api_key}")

    if not validate_api_key(api_key):
        logger.warning(f"无效的 API Key 尝试: {api_key}")
        return {"code": "401", "status": "error", "msg": "无效的 API Key"}

    logger.info(f"正在处理持仓信息: {positions}")
    # 构造企业微信消息
    markdown_content = f"""
    ### 📈 持仓调整操作通知  
    **操作类型**: `{positions.operation.upper()}`  
    **交易时间**: {positions.trade_time}  

    **股票信息**:{json.dumps(positions.stock_info, indent=2, ensure_ascii=False)}
    """
    # 发送企业微信通知
    send_message_to_qw(markdown_content)

    process_trade(positions.stock_info)
    # 模拟交易处理
    logger.info("持仓调整成功完成。")
    return {"code": "200", "status": "success", "data": "操作成功"}


def process_trade(positions):
    logger.info(f"接收到持仓信息: {positions}")

    qmt_core.qmt_execute(jukuan_positions=positions, exclude_codes_list=[])


def send_message_to_qw(markdown):
    # 设置Webhook URL
    url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=72d9674e-c75b-4c94-8d3f-426c6bcec659"
    # 创建请求负载
    payload = json.dumps({
        "msgtype": "markdown",
        "markdown": {
            "content": markdown
        }
    })

    # 设置请求头
    headers = {
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'Content-Type': 'application/json'
    }

    # 发送POST请求并处理响应
    try:
        response = requests.post(url, headers=headers, data=payload)
        response.raise_for_status()  # 检查请求是否成功
        print("消息发送成功:", response.text)
    except requests.exceptions.RequestException as e:
        print("消息发送失败:", e)
